﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ToolPositioningInternal.CUiTPIGenerateDatasetWindow
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using Newtonsoft.Json;
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui;
using Tecnomatix.Engineering.Ui.WPF;
using UiInternalControls.WPF;


namespace DnProcessSimulateCommands.ToolPositioningInternal;

public class CUiTPIGenerateDatasetWindow : TxWindow, IComponentConnector
{
  private readonly CApTPIViewModel _viewModel;
  private CApTPIDataGenerator _dataGenerator;
  private static ITxObject m_oldSelection;
  private Action callback;
  private bool StopButtonActivated;
  private Random random = new Random();
  internal DataGrid myDataGrid;
  internal TextBox dir;
  internal ComboBox insert_label;
  internal TextBox imageCount;
  internal ComboBox xLabel;
  internal TextBox xNumberOfImages;
  internal TextBox xSize;
  internal TxGraphicControl m_gv;
  private bool _contentLoaded;

  public CUiTPIGenerateDatasetWindow()
  {
    this.InitializeComponent();
    this._viewModel = new CApTPIViewModel()
    {
      TrainingSetDefinition = (IList<CApTPILabelParams>) new ObservableCollection<CApTPILabelParams>()
    };
    ((FrameworkElement) this).DataContext = (object) this._viewModel;
    this._dataGenerator = new CApTPIDataGenerator(this.dir.Text);
  }

  private void BrowseButton_Click(object sender, RoutedEventArgs e)
  {
    using (TxFolderBrowserDialog folderBrowserDialog = new TxFolderBrowserDialog())
    {
      folderBrowserDialog.InitialFolder = Environment.SpecialFolder.Desktop.ToString();
      if (folderBrowserDialog.ShowDialog() != 1)
        return;
      this.dir.Text = folderBrowserDialog.SelectedFolder;
    }
  }

  private void TxWindow_Closing(object sender, CancelEventArgs e)
  {
    this._dataGenerator.IsGenerationInProgress = false;
    if (this._dataGenerator.Object != null)
      this.m_gv.RemoveObject((ITxObject) this._dataGenerator.Object);
    this._dataGenerator.Object = (ITxLocatableObject) null;
  }

  private void Preview_Handler(object sender, RoutedEventArgs e)
  {
    CApTPILabelParams selectedRow = this._viewModel.SelectedRow;
    if (selectedRow == null || selectedRow.Object == null)
      return;
    this._dataGenerator.Object = selectedRow.Object as ITxLocatableObject;
    this.gv_replaceObject(selectedRow.Object);
    ((FrameworkElement) this.m_gv).Width = (double) selectedRow.Width;
    ((FrameworkElement) this.m_gv).Width = (double) selectedRow.Height;
    this.m_gv.AdjustCameraPosition(this._dataGenerator.ObjectApproachDirection);
  }

  private void Start_Click(object sender, RoutedEventArgs e)
  {
    if (string.IsNullOrEmpty(this.dir.Text))
    {
      int num1 = (int) MessageBox.Show("Please provide a 'Destination:' directory", "Missing destination folder", MessageBoxButton.OK, MessageBoxImage.Exclamation);
    }
    else
    {
      this._dataGenerator.OutputDirectory = this.dir.Text;
      TxApplication.ActiveDocument.Selection.Clear();
      int num2 = 0;
      foreach (CApTPILabelParams selected in (IEnumerable<CApTPILabelParams>) this._viewModel.TrainingSetDefinition)
      {
        this._dataGenerator.Object = selected.Object as ITxLocatableObject;
        this.gv_replaceObject(selected.Object);
        ((FrameworkElement) this.m_gv).Width = (double) selected.Width;
        ((FrameworkElement) this.m_gv).Height = (double) selected.Height;
        this.m_gv.AdjustCameraPosition(this._dataGenerator.ObjectApproachDirection);
        this._dataGenerator.GeneratingDataExampleCallBack = this.SaveImage_Handler(selected, num2++);
        this._dataGenerator.Generate(selected.NumberOfImages);
        this._dataGenerator.GeneratingDataExampleCallBack = (Action<ITxObject>) null;
        if (this.StopButtonActivated)
        {
          this.StopButtonActivated = false;
          break;
        }
      }
    }
  }

  private void Stop_Click(object sender, RoutedEventArgs e)
  {
    this._dataGenerator.IsGenerationInProgress = false;
    this.StopButtonActivated = true;
  }

  private Action<ITxObject> SaveImage_Handler(CApTPILabelParams selected, int idx)
  {
    return (Action<ITxObject>) (obj =>
    {
      if (!this._dataGenerator.IsGenerationInProgress)
        return;
      (selected.Object as ITxDisplayableObject).Color = CUiTPIGraphicControlHelper.PickRandomColor();
      this.m_gv.Refresh();
      using (Bitmap snapshot = this.m_gv.GetSnapshot(new System.Drawing.Size(selected.Width, selected.Height)))
      {
        if (snapshot == null)
          return;
        string filename = $"{selected.Label}_[{idx}]";
        this._dataGenerator.SaveImage((System.Drawing.Image) snapshot, filename, selected.Label);
      }
    });
  }

  private void SaveState_Click(object sender, RoutedEventArgs e)
  {
    var data = new
    {
      Folder = this.dir.Text,
      Data = this._viewModel.TrainingSetDefinition.Select(lbl => new
      {
        Name = lbl.Object.Name,
        Label = lbl.Label,
        NumberOfImages = lbl.NumberOfImages,
        Background = lbl.Background,
        Size = lbl.Size
      }).ToList()
    };
    File.WriteAllText("TrainingSet.json", JsonConvert.SerializeObject((object) data, (Formatting) 1));
  }

  private void RestoreState_Click(object sender, RoutedEventArgs e)
  {
    string str = File.ReadAllText("TrainingSet.json");
    var data1 = new
    {
      Folder = "",
      Data = new \u003C\u003Ef__AnonymousType2<string, string, int, string, string>[1]
      {
        new
        {
          Name = "",
          Label = "",
          NumberOfImages = 0,
          Background = "",
          Size = ""
        }
      }.ToList()
    };
    var data2 = JsonConvert.DeserializeAnonymousType(str, data1);
    this.dir.Text = data2.Folder;
    TxObjectList allDescendants = TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxComponent)));
    foreach (var data3 in data2.Data)
    {
      ITxComponent objectByName = this._GetObjectByName(data3.Name, allDescendants);
      this._viewModel.TrainingSetDefinition.Add(new CApTPILabelParams()
      {
        Object = (ITxObject) objectByName,
        Label = data3.Label,
        NumberOfImages = data3.NumberOfImages,
        Background = data3.Background,
        Size = data3.Size
      });
    }
  }

  private void UpdateSelected_Click(object sender, RoutedEventArgs e)
  {
    if (this.SelectedItems.Count == 0)
      return;
    foreach (CApTPILabelParams selectedItem1 in this.SelectedItems)
    {
      CApTPILabelParams selectedItem = selectedItem1;
      CApTPILabelParams capTpiLabelParams = this._viewModel.TrainingSetDefinition.FirstOrDefault<CApTPILabelParams>((Func<CApTPILabelParams, bool>) (x => x == selectedItem));
      if (capTpiLabelParams != null)
      {
        if (!string.IsNullOrEmpty(this.xLabel.Text))
          capTpiLabelParams.Label = this.xLabel.Text;
        int result;
        if (int.TryParse(this.xNumberOfImages.Text, out result))
          capTpiLabelParams.NumberOfImages = result;
        if (!string.IsNullOrEmpty(this.xSize.Text))
          capTpiLabelParams.Size = this.xSize.Text;
      }
    }
  }

  private void InsertSelection_Click(object sender, RoutedEventArgs e)
  {
    TxObjectList filteredItems = TxApplication.ActiveSelection.GetFilteredItems((ITxTypeFilter) new TxTypeFilter(typeof (ITxComponent)));
    string text = this.insert_label.Text;
    int result = 1;
    int.TryParse(this.imageCount.Text, out result);
    foreach (ITxComponent itxComponent in (Collection<ITxObject>) filteredItems)
      this._viewModel.TrainingSetDefinition.Add(new CApTPILabelParams()
      {
        Object = (ITxObject) itxComponent,
        Label = text,
        NumberOfImages = result
      });
  }

  internal List<CApTPILabelParams> SelectedItems
  {
    get
    {
      List<CApTPILabelParams> selectedItems = new List<CApTPILabelParams>();
      foreach (object selectedItem in (IEnumerable) this.myDataGrid.SelectedItems)
        selectedItems.Add(selectedItem as CApTPILabelParams);
      return selectedItems;
    }
  }

  internal ITxComponent _GetObjectByName(string name, TxObjectList objs)
  {
    return ((IEnumerable<ITxObject>) objs).Where<ITxObject>((Func<ITxObject, bool>) (x => x.Name == name)).FirstOrDefault<ITxObject>() as ITxComponent;
  }

  internal void gv_replaceObject(ITxObject newObject)
  {
    if (CUiTPIGenerateDatasetWindow.m_oldSelection != null)
      this.m_gv.RemoveObject(CUiTPIGenerateDatasetWindow.m_oldSelection);
    this.m_gv.AddObject(newObject);
    CUiTPIGenerateDatasetWindow.m_oldSelection = newObject;
  }

  internal void ZoomOut()
  {
    int num1 = -120;
    System.Drawing.Point point = new System.Drawing.Point((int) ((FrameworkElement) this.m_gv).Width / 2, (int) ((FrameworkElement) this.m_gv).Height / 2);
    double num2 = Math.Pow(1.25, (double) (num1 / 120) * 1.5);
    System.Drawing.Size size = new System.Drawing.Size((int) ((FrameworkElement) this.m_gv).Width, (int) ((FrameworkElement) this.m_gv).Height);
    double num3 = (double) size.Width * (1.0 - 1.0 / num2);
    double num4 = (double) size.Height * (1.0 - 1.0 / num2);
    double num5 = (double) point.X / (double) size.Width;
    double num6 = (double) point.Y / (double) size.Height;
    Rectangle rectangle = new Rectangle((int) (num5 * num3), (int) (num6 * num4), (int) ((double) size.Width - num3), (int) ((double) size.Height - num4));
    this.m_gv.ZoomByWindow(new Rectangle(rectangle.Left, size.Height - rectangle.Top, rectangle.Right - rectangle.Left, rectangle.Top - rectangle.Bottom));
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  public void InitializeComponent()
  {
    if (this._contentLoaded)
      return;
    this._contentLoaded = true;
    Application.LoadComponent((object) this, new Uri("/DnProcessSimulateCommands;component/toolpositioninginternal/cuitpigeneratedatasetwindow.xaml", UriKind.Relative));
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IComponentConnector.Connect(int connectionId, object target)
  {
    switch (connectionId)
    {
      case 1:
        ((ButtonBase) target).Click += new RoutedEventHandler(this.RestoreState_Click);
        break;
      case 2:
        ((ButtonBase) target).Click += new RoutedEventHandler(this.SaveState_Click);
        break;
      case 3:
        ((ButtonBase) target).Click += new RoutedEventHandler(this.Start_Click);
        break;
      case 4:
        ((ButtonBase) target).Click += new RoutedEventHandler(this.Stop_Click);
        break;
      case 5:
        this.myDataGrid = (DataGrid) target;
        this.myDataGrid.SelectionChanged += new SelectionChangedEventHandler(this.Preview_Handler);
        break;
      case 6:
        this.dir = (TextBox) target;
        break;
      case 7:
        ((ButtonBase) target).Click += new RoutedEventHandler(this.BrowseButton_Click);
        break;
      case 8:
        ((ButtonBase) target).Click += new RoutedEventHandler(this.InsertSelection_Click);
        break;
      case 9:
        this.insert_label = (ComboBox) target;
        break;
      case 10:
        this.imageCount = (TextBox) target;
        break;
      case 11:
        ((ButtonBase) target).Click += new RoutedEventHandler(this.UpdateSelected_Click);
        break;
      case 12:
        this.xLabel = (ComboBox) target;
        break;
      case 13:
        this.xNumberOfImages = (TextBox) target;
        break;
      case 14:
        this.xSize = (TextBox) target;
        break;
      case 15:
        this.m_gv = (TxGraphicControl) target;
        break;
      default:
        this._contentLoaded = true;
        break;
    }
  }
}
